/**
 * 
 */
package com.action;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.client.cache.IPayOrderManager;
import com.client.cache.IPayOrderStatusManager;
import com.client.cache.ISpCodeManager;
import com.client.cache.PhoneNumberManager;
import com.client.cache.PhoneNumberThread;
import com.client.cache.UserManager;
import com.client.model.IPayOrder;
import com.client.model.ISpCodeProvince;
import com.client.model.IniResponse;
import com.client.model.User;
import com.filter.BlackListFilter;
import com.filter.SystemLimitFilter;
import com.manage.cache.CpAppInfoManager;
import com.manage.model.CpAppInfo;
import com.util.Base64;
import com.util.PayErrorCode;
import com.util.PayRequestParameter;
import com.util.ProvinceUtil;
import com.util.RegionUtil;
import com.util.Util;
import com.util.ZipHelper;

public class UPayAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	public String execute() {
		return null;
	}
	/**
	 * 
	 *opcode=5001&userid=1&imei=869717010036506&mac=68:9c:5e:30:96:81&
	 *imsi=460023865014243&simsn=8986002823118a594243&operator=46002
	 *&smsc=+8613800851503;+8613800852502&mobile=&net=wifi&
	 *appid=APQW12DSS5&chid=CH123456&
	 *package=com.example.demo&version=1.2.0.2&
	 *appflag=572998&md5=89c52ef4aa85f494a54f6a36261292e5&
	 *location=/data/app/com.example.demo-2.apk&
	 *android_id=e49629eb92a95628&board=signal77_ics2
	 *&manufacturer=alps&device=signal77_ics2&
	 *product=YOUPU U6&model=YOUPU U6
	 *&brand=alps&sdk=15&sdk_int=15&release=4.1.1&code=demo&name=示例&fee=500

	 */
	public UPayAction() {
		time = System.currentTimeMillis();
	}
	
	private long time;

	public String order()
	{
		//return out(resultStr.toString().replace("&", "&amp;"));
		Map<String, String> requestMap =null;
		try {
			String str = getInputStreamAsString();
			logger.info("request thread:" + Thread.currentThread().getName() + " POST:" + str);
			requestMap = PayRequestParameter.getRequestParameter(new String(ZipHelper.unzip((Base64.decode(str, Base64.DEFAULT))),"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		IniResponse inir = new IniResponse();
		String errorcode = "";
		if(requestMap==null)
		{
			errorcode = PayErrorCode.RESPONSE_PARAM_ERROR;
		}else
		{
			logger.info("pay"+" "+Util.dateToString(new Date())+" pay request Parameter -- ["+requestMap.toString()+"]");
			
			//判断参数，如果参数不符合直接返回
			errorcode = PayRequestParameter.checkRequestParameter(requestMap);
		}
		if(errorcode!=null && errorcode.length()>0)
			return out(inir.generatenull(errorcode,requestMap.get("fee")));
		String productid = "";
		String extchid = "";
		String cpid = "";
		//验证SDK版本、分配的APP等信息
		CpAppInfo cpapp = CpAppInfoManager.getInstance().getCpAppInfoByAppNumber(requestMap.get("appid"));
		if(cpapp==null || !cpapp.getAppstatus().equals("0"))
		{
			errorcode = PayErrorCode.RESPONSE_APP_ERROR;
		}else
		{
			if(requestMap.get("package").equals(cpapp.getApppackage().trim()))
			{
				productid = ""+cpapp.getProjectid();
				extchid = ""+cpapp.getChannelid();
				cpid = ""+cpapp.getCpid();
			}else
			{
				errorcode = PayErrorCode.RESPONSE_APP_ERROR;
			}
		}
		if(errorcode!=null && errorcode.length()>0)
			return out(inir.generatenull(errorcode,requestMap.get("fee")));
		
		if(productid.equals("") || productid.equals("0"))
			productid = "-1";
		if(extchid.equals("") || extchid.equals("0"))
			extchid = "-1";
		if(cpid.equals("") || cpid.equals("0"))
			cpid = "-1";
		
		
		if(requestMap.get("mobile") ==null || requestMap.get("mobile").length()<=0)
		{
			String number = PhoneNumberManager.getInstance().getPhoneNumberByImsi(requestMap.get("imsi"));
			if(number==null || "".equals(number))
			{
				//errorcode = PayErrorCode.RESPONSE_UNKNOWN_AREA_ERROR;
				//return out(inir.generatenumbernull(errorcode));
			}else
			{
				requestMap.put("mobile", number);
			}
		}

		//生成user

		User user = new User(-1, 
				java.util.UUID.randomUUID().toString().replace("-", ""), 
				requestMap.get("mobile"), requestMap.get("imsi"), requestMap.get("imei"), 
				requestMap.get("smsc"), "", -1, Integer.parseInt(extchid), 
				Integer.parseInt(productid), "", "", -1,requestMap.get("version"),
				requestMap.get("android_id"),requestMap.get("board"),requestMap.get("manufacturer"),
				requestMap.get("device"),requestMap.get("product"),requestMap.get("model"),requestMap.get("sdk"),
				requestMap.get("sdk_int"),requestMap.get("release"),requestMap.get("simsn"),
				requestMap.get("mac"),Integer.parseInt(cpid),requestMap.get("appid"),requestMap.get("chid"));
		
		UserManager.getInstance().handle(user);
		//System.out.println(user.getMobile()+" "+user.getProvince()+" "+user.getRegion());
		
		/**
		 * 0正常下发
		 * 1 黑名单
		 * 2、超系统日月限
		 * 3、没有匹配到省份
		 * 4、没有可用代码
		 * public class PayErrorCode {
	public static final String RESPONSE_PARAM_ERROR = "110000";  //参数错误
    public static final String RESPONSE_MONEY_ERROR = "110001";  //请求金额错误
    public static final String RESPONSE_NO_CHANNEL_ERROR = "110002"; //没有部署通道
    public static final String RESPONSE_UNKNOWN_AREA_ERROR = "110003"; //省份匹配错误

    public static final String RESPONSE_APP_ERROR = "110004";         //app验证没通过
    public static final String RESPONSE_CHANNEL_ERROR = "110005";	  //匹配不到相应的通道
    public static final String RESPONSE_BLACK_USER = "110006";		  //黑名单
    public static final String RESPONSE_BLACK_USER = "110007";        //系统日月限
}
		 */
		
		//2、计费次数，是否超系统设置单手机日月限制
		if(requestMap.get("fee").equals("47"))
		{
			if(SystemLimitFilter.getInstance().isSystemLimit(user.getMobile(), user.getImsi(), user.getImei(),extchid,productid))
			{
				logger.error(Util.dateToString(new Date())+" user " + user.toLogString()+" is SystemLimitFilter");
				errorcode = PayErrorCode.RESPONSE_SYSTEM_LIMIT;
			}
		}
		//1、过滤黑名单
		if(user.getMobile()!=null && user.getMobile().length()>0)
		{
			
			if(BlackListFilter.getInstance().isBlack(user.getMobile()))
			{
				logger.error("enginname:kypay"+" "+Util.dateToString(new Date())+" user" + user.toLogString()+" is black");

				errorcode = PayErrorCode.RESPONSE_BLACK_USER;
			}
		}
		//3、匹配省份
		if(errorcode.equals("")&&(user.getProvince()==null || user.getProvince().trim().equals("") || user.getProvince().trim().equals("UNKN")))
		{
			logger.error("enginname:kypay"+" "+Util.dateToString(new Date())+" user " + user.toLogString()+" no province");

			errorcode = PayErrorCode.RESPONSE_UNKNOWN_AREA_ERROR;
		}
		//4、取可用代码，返回。
		ISpCodeProvince icp = null;
		if(errorcode.equals(""))
		{
			icp = ISpCodeManager.getInstance().getIProductCodeByUserPay(user.getCarrier(), user.getProvince(), user.getRegion(),
					requestMap.get("mobile"),requestMap.get("imsi"),requestMap.get("net"),requestMap.get("fee"));
			if(icp==null)
			{
	
				logger.error("enginname:kypay"+" "+Util.dateToString(new Date())+" user " + user.toLogString()+" no code");
	
				errorcode = PayErrorCode.RESPONSE_CHANNEL_ERROR;
			}
		}
		//如果所有验证通过，则去处理返回信息
		String responseStr = "";
		if(errorcode.equals(""))
		{
			//保存订单
			String regionCode = RegionUtil.getInstance().getRegionByRegionName(icp.getProvinceCode(), user.getRegion());
			//int cpid,String appid,String goodscode,String goodsname,String chid
			IPayOrder order = new IPayOrder(user.getId(), user.getMobile(), icp.getCarrier(), icp.getOrderType(),
					icp.getCodeType(), icp.getSpId(), icp.getId(), icp.getProvinceCode(), regionCode,
					icp.getFeeValue(), user.getChannelId(), user.getProjectId(),
					new Date(), new Date()
					,Integer.parseInt(cpid),requestMap.get("appid")
					,requestMap.get("code"),requestMap.get("name")
					,requestMap.get("chid"),requestMap.get("fee"),"0",user.getImsi());
			//扔到队列处理订单
			IPayOrderManager.getInstance().handle(order);
			//处理返回字符串
	
			responseStr = inir.generate(icp,order,errorcode);
		}
		else
		{
			//没有代码，生成一个空的订单
			String provinceCode = ProvinceUtil.getInstance().getProvinceByName(user.getProvince());
//			[carrier]
//			 CMCC = 中国移动
//			 UNICOM = 中国联通
//			 TELECOM = 中国电信
			String carrierCode = "";
			if(user.getCarrier()!=null)
			{
				if(user.getCarrier().indexOf("移动")>-1)
					carrierCode="CMCC";
				else if(user.getCarrier().indexOf("联通")>-1)
					carrierCode="UNICOM";
				else if(user.getCarrier().indexOf("电信")>-1)
					carrierCode="TELECOM";
			}
			String regionCode = RegionUtil.getInstance().getRegionByRegionName(provinceCode, user.getRegion());
			IPayOrder order = new IPayOrder(user.getId(), user.getMobile(), carrierCode, "-1",
					"-1",-1, -1, provinceCode, regionCode,
					"0", user.getChannelId(), user.getProjectId(),
					new Date(), new Date(),Integer.parseInt(cpid),requestMap.get("appid")
					,requestMap.get("code"),requestMap.get("name")
					,requestMap.get("chid"),requestMap.get("fee"),"0",user.getImsi());
			order.setReport(Integer.parseInt(errorcode));
//			//扔到队列处理订单
			IPayOrderManager.getInstance().handle(order);
			responseStr = inir.generatenull(order,errorcode);
		}
		logger.info("enginname:kypay"+" "+Util.dateToString(new Date())+" ["+requestMap.toString()+"] pay request Parameter -- result:"+errorcode);
		return out(responseStr);
	}

	public String r()
	{
		//v={version}&svid={serviceid}&exid={extchid}&pid={productid}&cct=1&mo={number}
		Map<String, String> requestMap = null;
		try {
			String str = getInputStreamAsString();
			requestMap = PayRequestParameter.getRequestParameter(new String(ZipHelper.unzip((Base64.decode(str, Base64.DEFAULT))),"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		//String orderId,String suborderId,int report, Date reportTime
		if(requestMap!=null)
		{
			logger.info("payreport"+" "+Util.dateToString(new Date())+" payreport request Parameter -- ["+requestMap.toString()+"]");
			IPayOrder order = new IPayOrder(requestMap.get("orderid")
					,""
					, Integer.parseInt(requestMap.get("report")), new Date(),"0");
			IPayOrderStatusManager.getInstance().handle(order);
		}
		String responseStr = "ok";
		return out(responseStr);
	}
	
	private String out(String rsp)
	{
		try {
			//rsp = Base64.encode(rsp.getBytes("UTF-8"));
			rsp = rsp.replace("${host}", request.getServerName()+":"+request.getServerPort());
			String s =  new String(Base64.encode(
					ZipHelper.zip(rsp.getBytes()), Base64.DEFAULT),"utf-8");
			System.out.println(s);
			setContentLength(s.getBytes("utf-8").length);
			setContentType("text/plain;charset=utf-8");
			PrintWriter pw = getResponse().getWriter();
			pw.write(s);
			pw.flush();
			pw.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		logger.info("thread: " + Thread.currentThread().getName() + ";cost: " + (System.currentTimeMillis() - time) + ";response:" + rsp.replace("\r", "\\r").replace("\n", "\\n"));
		return null;
	}
	public String imsi()
	{
		String mobile = getParameter("mobile");
		String imsi = getParameter("imsi");
		if(mobile!=null && imsi!=null && mobile.length()>0 && imsi.length()>0)
		{
			if(mobile.indexOf("+86")>-1)
				mobile = mobile.replace("+86", "");
			if(mobile.startsWith("86"))
			{
				mobile = mobile.substring(2,mobile.length());
			}
			new PhoneNumberThread(mobile, imsi).start();
			
		}
		String responseStr = "ok";
		return out(responseStr);
	}
	
	
}
